package com.tbvtc.agriculturalcreditchainserver2025.utils;

import org.dhatim.fastexcel.Workbook;
import org.dhatim.fastexcel.Worksheet;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ExcelExportUtil {

    /**
     * 导出Excel文件
     * @param fileName 文件名
     * @param sheetName 工作表名
     * @param headers 表头数组
     * @param dataList 数据列表(每行数据是一个Map,key对应表头)
     * @return ResponseEntity<byte[]>
     */
    public static ResponseEntity<byte[]> exportExcel(String fileName, String sheetName, 
            String[] headers, List<Map<String, Object>> dataList) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 创建工作簿和工作表
            Workbook workbook = new Workbook(outputStream, "AgriculturalCreditChain", "1.0");
            Worksheet worksheet = workbook.newWorksheet(sheetName);
            
            // 写入表头
            for (int i = 0; i < headers.length; i++) {
                worksheet.value(0, i, headers[i]);
            }
            
            // 写入数据
            for (int row = 0; row < dataList.size(); row++) {
                Map<String, Object> rowData = dataList.get(row);
                for (int col = 0; col < headers.length; col++) {
                    Object value = rowData.get(headers[col]);
                    worksheet.value(row + 1, col, value != null ? value.toString() : "");
                }
            }
            
            // 完成写入
            workbook.finish();
            
            // 构建响应
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName + ".xlsx")
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .body(outputStream.toByteArray());
                    
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }
}
